import os
import glfw
import OpenGL.GL as GL
import datetime
from PIL import Image
from Constants import SCREEN_SHOT_SAVE_PATH
from AudioManager import audio_player
from Utils import logger

"""
截图管理器
"""


def take_screen_shot(window):
    if not os.path.exists(SCREEN_SHOT_SAVE_PATH):
        os.makedirs(SCREEN_SHOT_SAVE_PATH)
    # 获取帧缓冲区大小
    width, height = glfw.get_framebuffer_size(window)
    # 读取像素数据 (RGB格式)
    GL.glPixelStorei(GL.GL_PACK_ALIGNMENT, 1)
    buffer = GL.glReadPixels(0, 0, width, height, GL.GL_RGB, GL.GL_UNSIGNED_BYTE)

    # 转换为PIL图像并保存
    image = Image.frombytes("RGB", (width, height), buffer)
    image = image.transpose(Image.Transpose.FLIP_TOP_BOTTOM)  # OpenGL的缓冲区是倒置的

    save_path = os.path.join(
        SCREEN_SHOT_SAVE_PATH,
        f"screenshot_{datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")}.png"
    )

    image.save(save_path)
    logger.info(f"截图已保存为: {save_path}")
    audio_player.play_sound("screenshot")
